package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

/**
 * 测试定时任务通过okhttp方式来请求restful接口，来实现动态添加任务调度
 */
@JobHander(value="okhttpJobHandler")
@Service
public class OkhttpJobHandler extends IJobHandler {


    @Override
    public ReturnT<String> execute(String... params) throws Exception {

        if (params == null || params.length == 0) {
            return ReturnT.FAIL;
        }

        for (String param : params) {
            System.out.println(param);
        }

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(params[0]).get()
                .addHeader("cache-control", "no-cache")
                .build();

        Response response = client.newCall(request).execute();

        System.out.println(response.code());
        System.out.println(response.body().string());

        if (ReturnT.SUCCESS_CODE == response.code()) {
            return ReturnT.SUCCESS;
        }else{
            return ReturnT.FAIL;
        }
    }
}
